using System;
using System.Data;
using System.Data.SqlClient;

namespace DataAccessLayer
{
	public class ArtistGateway
	{
		private SqlDataAdapter adapter; 
		private SqlConnection connection;
		private SqlCommand command;
		private SqlCommandBuilder builder;

		public ArtistGateway(SqlConnection connection)
		{
            this.connection = connection;
			command = new SqlCommand("select id, name from artist where id = @id", connection);
			command.Parameters.Add("@id", SqlDbType.BigInt);

			adapter = new SqlDataAdapter(command);
			builder = new SqlCommandBuilder(adapter);
		}

        public long Insert(string artistName, RecordingDataSet recordingDataSet) {
            RecordingDataSet.ArtistRow newArtist = recordingDataSet.Artist.NewArtistRow();
            newArtist.name = artistName;
            newArtist.id = IdGenerator.GetNextId(recordingDataSet.Artist.TableName, connection);
            recordingDataSet.Artist.AddArtistRow(newArtist);
            Update(recordingDataSet);
            return newArtist.id;
        
        }

		public RecordingDataSet.ArtistRow FindById(long artistId, RecordingDataSet recordingDataSet)
		{
            command.Parameters["@id"].Value = artistId;
            adapter.Fill(recordingDataSet, recordingDataSet.Artist.TableName);
            DataRow[] rows = recordingDataSet.Artist.Select(String.Format("id={0}", artistId));

            if(rows.Length<1) return null;

            return (RecordingDataSet.ArtistRow)rows[0];

		}

        public void Delete(long artistId, RecordingDataSet recordingDataSet)
		{
            DataRow loadedArtist = FindById(artistId, recordingDataSet);
            loadedArtist.Delete();
            Update(recordingDataSet);
		}

		public void Update(RecordingDataSet recordingDataSet)
		{
            adapter.Update(recordingDataSet, recordingDataSet.Artist.TableName);
		}
	}
}
